# == Schema Information
# Schema version: 22
#
# Table name: disciplines
#
#  id                :integer       not null, primary key
#  name              :string(255)
#  description       :text
#  created_at        :datetime
#  user_id           :integer
#  college_id        :integer
#  memberships_count :integer       default(0)
#

class Discipline < ActiveRecord::Base
  belongs_to :user
  belongs_to :college
  has_many :memberships, :dependent => :destroy

  has_many :discussions, :order => 'replied_at DESC', :dependent => :destroy do
    def comments(limit = nil)
      find(:all, :include => 'comments', :limit => limit)
    end
  end

  has_many :articles, :order => 'articles.created_at DESC', :dependent => :destroy do
    def recent(limit = nil)
      find(:all, :limit => limit)
    end

    def comments(limit = nil)
      find(:all, :include => 'comments', :limit => limit)
    end
  end

  has_many :users, :through => :memberships, :order => 'memberships.created_at DESC' do
    def recent(limit = nil)
      find(:all, :limit => limit)
    end
  end

  validates_presence_of :name, :description, :college, :user
  validates_uniqueness_of :name

  def self.find_all_by_membership_count(limit = 10)
    find(:all, :order => 'memberships_count desc', :limit => limit)
  end

  def self.build_search(term)
    term = "%#{term.downcase}%"
    where = self.find_where_options :inner => { :discipline => :or } do |d|
      d.name.downcase =~ term
      d.description.downcase  =~ term
    end
    where[:conditions]
  end

end
